<template>
  <div class="pdf-viewer">
    <div class="pdf-toolbar">
      <div class="pdf-info">
        <span class="pdf-title">2022-05-24_15_07_32-房屋买卖合同.pdf</span>
        <span class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      </div>
      <div class="pdf-controls">
        <el-button-group>
          <el-button :disabled="currentPage <= 1" @click="prevPage">
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          <el-button :disabled="currentPage >= totalPages" @click="nextPage">
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </el-button-group>
        <el-select v-model="scale" @change="onScaleChange" style="width: 100px; margin-left: 10px;">
          <el-option label="50%" :value="0.5" />
          <el-option label="75%" :value="0.75" />
          <el-option label="100%" :value="1" />
          <el-option label="125%" :value="1.25" />
          <el-option label="150%" :value="1.5" />
          <el-option label="200%" :value="2" />
        </el-select>
      </div>
    </div>
    
    <div class="pdf-content" ref="pdfContainer">
      <div class="pdf-page-container" ref="pageContainer">
        <canvas ref="pdfCanvas" class="pdf-canvas"></canvas>
        
        <!-- 骑缝章位置指示器 -->
        <div v-if="showRidingStamp" class="riding-stamp-indicator" :style="ridingStampStyle">
          <div class="riding-stamp-line"></div>
          <div class="riding-stamp-preview">
            <el-icon class="stamp-icon"><Stamp /></el-icon>
          </div>
        </div>
        
        <!-- 可拖拽的签署位元素 -->
        <draggable
          v-model="signatureElements"
          :group="{ name: 'signatures', pull: false, put: true }"
          item-key="id"
          class="signature-overlay"
          @add="onSignatureAdd"
        >
          <template #item="{ element }">
            <div 
              :class="['signature-element', element.type, { 'is-selected': selectedSignatureId === element.id }]"
              :style="{
                left: element.x + 'px',
                top: element.y + 'px',
                width: element.width + 'px',
                height: element.height + 'px'
              }"
              @click="selectSignature(element.id)"
            >
              <div class="signature-content">
                <el-icon v-if="element.type === 'signature'" class="signature-icon">
                  <Star />
                </el-icon>
                <!-- 自定义印章显示 -->
                <div v-else-if="element.type === 'stamp'" 
                     class="custom-stamp" 
                     :class="element.stampShape || 'circle'"
                     :style="{
                       color: element.stampColor || '#FF0000',
                       borderColor: element.stampColor || '#FF0000',
                       borderWidth: (element.stampBorderWidth || 2) + 'px',
                       fontSize: (element.stampFontSize || 12) + 'px'
                     }">
                  {{ element.stampText || '福建雄翔建设发展有限公司' }}
                </div>
                <span v-else-if="element.type === 'text'">{{ element.content || '文本签署' }}</span>
                <span v-else-if="element.type === 'date'">{{ element.content || '日期签署' }}</span>
              </div>
              <div class="signature-controls" v-if="selectedSignatureId === element.id">
                <el-button-group>
                  <el-button size="small" type="primary" @click.stop="editSignature(element.id)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button size="small" type="danger" @click.stop="removeSignature(element.id)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
              <div class="resize-handle" v-if="selectedSignatureId === element.id" @mousedown.stop="startResize($event, element.id)"></div>
            </div>
          </template>
        </draggable>
      </div>
    </div>
    
    <!-- 签署位编辑对话框 -->
    <SignatureEditDialog
      v-model="editDialogVisible"
      :signature="currentEditingSignature"
      :A4Width="A4_WIDTH"
      @confirm="saveSignatureEdit"
      @ridingStampChange="handleRidingStampChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ArrowLeft, ArrowRight, Star, Delete, Edit, Stamp } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import * as pdfjsLib from 'pdfjs-dist'
import SignatureEditDialog from './SignatureEditDialog.vue'

// 设置PDF.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'

// A4纸尺寸（595 x 842 像素，72dpi）
const A4_WIDTH = 595
const A4_HEIGHT = 842

/**
 * 签署位元素接口
 */
interface SignatureElement {
  id: string
  type: 'signature' | 'text' | 'date' | 'stamp'
  x: number
  y: number
  width: number
  height: number
  content?: string
  isRidingStamp?: boolean
  // 印章相关属性
  stampText?: string
  stampColor?: string
  stampShape?: 'circle' | 'square'
  stampBorderWidth?: number
  stampFontSize?: number
}

// PDF相关状态
const pdfContainer = ref<HTMLElement>()
const pageContainer = ref<HTMLElement>()
const pdfCanvas = ref<HTMLCanvasElement>()
const currentPage = ref(1)
const totalPages = ref(0)
const scale = ref(1)
const pdfDoc = ref<any>(null)

// 签署位相关状态
const signatureElements = ref<SignatureElement[]>([])
const selectedSignatureId = ref<string | null>(null)

// 编辑对话框状态
const editDialogVisible = ref(false)
const currentEditingSignature = ref<SignatureElement | null>(null)

// 骑缝章状态
const showRidingStamp = ref(false)
const ridingStampStyle = computed(() => {
  return {
    height: `${pageContainer.value?.clientHeight || 0}px`,
    left: `${A4_WIDTH / 2}px`
  }
})

// 调整大小状态
const isResizing = ref(false)
const resizingId = ref<string | null>(null)
const startResizePos = reactive({ x: 0, y: 0 })
const startResizeSize = reactive({ width: 0, height: 0 })



/**
 * 初始化PDF查看器
 */
const initPdfViewer = async () => {
  try {
    // 加载真实的PDF文件
    const loadingTask = pdfjsLib.getDocument('/sample.pdf')
    pdfDoc.value = await loadingTask.promise
    
    // 确保PDF文档已正确加载
    if (pdfDoc.value && pdfDoc.value.numPages > 0) {
      totalPages.value = pdfDoc.value.numPages
      currentPage.value = 1
      await renderPage(currentPage.value)
    } else {
      throw new Error('PDF文档无效或为空')
    }
  } catch (error) {
    console.error('PDF加载失败:', error)
    // 如果PDF加载失败，显示占位内容
    renderPlaceholder()
  }
}

/**
 * 渲染PDF页面
 * @param pageNum 页码
 */
const renderPage = async (pageNum: number) => {
  if (!pdfDoc.value || !pdfCanvas.value) {
    console.warn('PDF文档或画布未准备就绪')
    return
  }
  
  // 验证页码范围
  if (pageNum < 1 || pageNum > pdfDoc.value.numPages) {
    console.error('页码超出范围:', pageNum)
    return
  }
  
  try {
    const page = await pdfDoc.value.getPage(pageNum)
  
    // 使用A4尺寸，并根据缩放比例调整
    const viewport = page.getViewport({ scale: scale.value })
    
    // 计算缩放比例，使宽度为A4_WIDTH
    const scaleRatio = A4_WIDTH / viewport.width
    const adjustedScale = scale.value * scaleRatio
    
    // 使用调整后的缩放比例重新创建视口
    const adjustedViewport = page.getViewport({ scale: adjustedScale })
    
    const canvas = pdfCanvas.value
    const context = canvas.getContext('2d')
    
    if (!context) {
      throw new Error('无法获取画布上下文')
    }
    
    canvas.height = adjustedViewport.height
    canvas.width = A4_WIDTH // 固定为A4宽度
    
    // 更新容器尺寸
    if (pageContainer.value) {
      pageContainer.value.style.width = `${A4_WIDTH}px`
      pageContainer.value.style.height = `${adjustedViewport.height}px`
    }
    
    const renderContext = {
      canvasContext: context,
      viewport: adjustedViewport
    }
    
    await page.render(renderContext).promise
  } catch (error) {
    console.error('渲染PDF页面失败:', error)
    // 如果渲染失败，显示占位内容
    renderPlaceholder()
  }
}

/**
 * 渲染占位内容（当没有PDF时）
 */
const renderPlaceholder = () => {
  if (!pdfCanvas.value || !pageContainer.value) return
  
  const canvas = pdfCanvas.value
  const context = canvas.getContext('2d')
  if (!context) return
  
  // 设置画布尺寸为A4纸的尺寸
  canvas.width = A4_WIDTH
  canvas.height = A4_HEIGHT
  
  pageContainer.value.style.width = `${A4_WIDTH}px`
  pageContainer.value.style.height = `${A4_HEIGHT}px`
  
  // 绘制白色背景
  context.fillStyle = '#ffffff'
  context.fillRect(0, 0, canvas.width, canvas.height)
  
  // 绘制边框
  context.strokeStyle = '#e4e7ed'
  context.lineWidth = 2
  context.strokeRect(0, 0, canvas.width, canvas.height)
  
  context.fillStyle = '#909399'
  context.font = '16px Arial'
  context.textAlign = 'center'
  context.fillText('PDF预览区域 (A4尺寸)', canvas.width / 2, canvas.height / 2)
  
  // 绘制页码信息
  context.font = '14px Arial'
  context.fillText(`第 ${currentPage.value} 页，共 ${totalPages.value} 页`, canvas.width / 2, canvas.height - 30)
}

/**
 * 上一页
 */
const prevPage = async () => {
  if (currentPage.value > 1) {
    currentPage.value--
    await renderPage(currentPage.value)
  }
}

/**
 * 下一页
 */
const nextPage = async () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    await renderPage(currentPage.value)
  }
}

/**
 * 缩放变化处理
 */
const onScaleChange = async () => {
  await renderPage(currentPage.value)
}

/**
 * 添加签署位元素
 * @param evt 拖拽事件
 */
const onSignatureAdd = (evt: any) => {
  const newElement = signatureElements.value[signatureElements.value.length - 1]
  
  // 如果是印章类型，设置默认印章属性
  if (newElement.type === 'stamp') {
    // 设置默认印章属性
    newElement.stampText = '福建雄翔建设发展有限公司'
    newElement.stampColor = '#FF0000'
    newElement.stampShape = 'circle'
    newElement.stampBorderWidth = 2
    newElement.stampFontSize = 12
    newElement.isRidingStamp = false
    
    // 检查是否已有骑缝章
    const existingRidingStamp = signatureElements.value.find(el => 
      el.type === 'stamp' && el.isRidingStamp && el.id !== newElement.id
    )
    
    if (!existingRidingStamp) {
      newElement.x = A4_WIDTH / 2 - newElement.width / 2
    }
  }
  
  // 选中新添加的元素
  selectSignature(newElement.id)
}

/**
 * 选择签署位
 * @param id 签署位ID
 */
const selectSignature = (id: string) => {
  selectedSignatureId.value = selectedSignatureId.value === id ? null : id
}

/**
 * 删除签署位
 * @param id 签署位ID
 */
const removeSignature = (id: string) => {
  const index = signatureElements.value.findIndex(el => el.id === id)
  if (index > -1) {
    const element = signatureElements.value[index]
    
    // 如果删除的是骑缝章，需要隐藏骑缝章指示器
    if (element.type === 'stamp' && element.isRidingStamp) {
      showRidingStamp.value = false
    }
    
    signatureElements.value.splice(index, 1)
  }
  selectedSignatureId.value = null
}

/**
 * 编辑签署位
 * @param id 签署位ID
 */
const editSignature = (id: string) => {
  const element = signatureElements.value.find(el => el.id === id)
  if (element) {
    // 设置当前编辑的签署位
    currentEditingSignature.value = { ...element }
    editDialogVisible.value = true
  }
}

/**
 * 保存签署位编辑
 * @param editedSignature 编辑后的签署位数据
 */
const saveSignatureEdit = (editedSignature: SignatureElement) => {
  const index = signatureElements.value.findIndex(el => el.id === editedSignature.id)
  if (index > -1) {
    // 更新元素数据
    signatureElements.value[index] = { ...editedSignature }
    
    // 如果是骑缝章，更新骑缝章状态
    if (editedSignature.type === 'stamp' && editedSignature.isRidingStamp) {
      // 将其他骑缝章设置为非骑缝章
      signatureElements.value.forEach(el => {
        if (el.id !== editedSignature.id && el.type === 'stamp' && el.isRidingStamp) {
          el.isRidingStamp = false
        }
      })
      showRidingStamp.value = true
    }
  }
}

/**
 * 处理骑缝章状态变化
 * @param isRidingStamp 是否为骑缝章
 */
const handleRidingStampChange = (isRidingStamp: boolean) => {
  if (isRidingStamp) {
    showRidingStamp.value = true
  } else {
    // 检查是否还有其他骑缝章
    const hasOtherRidingStamp = signatureElements.value.some(el => 
      el.id !== currentEditingSignature.value?.id && el.type === 'stamp' && el.isRidingStamp
    )
    
    if (!hasOtherRidingStamp) {
      showRidingStamp.value = false
    }
  }
}



/**
 * 开始调整大小
 * @param event 鼠标事件
 * @param id 签署位ID
 */
const startResize = (event: MouseEvent, id: string) => {
  event.preventDefault()
  event.stopPropagation()
  
  const element = signatureElements.value.find(el => el.id === id)
  if (!element) return
  
  isResizing.value = true
  resizingId.value = id
  
  startResizePos.x = event.clientX
  startResizePos.y = event.clientY
  startResizeSize.width = element.width
  startResizeSize.height = element.height
  
  // 添加全局事件监听
  document.addEventListener('mousemove', onResize)
  document.addEventListener('mouseup', stopResize)
}

/**
 * 调整大小过程
 * @param event 鼠标事件
 */
const onResize = (event: MouseEvent) => {
  if (!isResizing.value || !resizingId.value) return
  
  const element = signatureElements.value.find(el => el.id === resizingId.value)
  if (!element) return
  
  const deltaX = event.clientX - startResizePos.x
  const deltaY = event.clientY - startResizePos.y
  
  // 计算新尺寸，并设置最小值
  const newWidth = Math.max(20, startResizeSize.width + deltaX)
  const newHeight = Math.max(20, startResizeSize.height + deltaY)
  
  // 更新元素尺寸
  element.width = newWidth
  element.height = newHeight
}

/**
 * 停止调整大小
 */
const stopResize = () => {
  isResizing.value = false
  resizingId.value = null
  
  // 移除全局事件监听
  document.removeEventListener('mousemove', onResize)
  document.removeEventListener('mouseup', stopResize)
}

// 组件挂载时初始化
onMounted(async () => {
  await nextTick()
  await initPdfViewer()
})
</script>

<style scoped>
.pdf-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pdf-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
}

.pdf-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.pdf-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.page-info {
  font-size: 12px;
  color: #909399;
}

.pdf-controls {
  display: flex;
  align-items: center;
}

.pdf-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.pdf-page-container {
  position: relative;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.pdf-canvas {
  display: block;
  background: white;
}

/* 骑缝章指示器 */
.riding-stamp-indicator {
  position: absolute;
  top: 0;
  width: 2px;
  background-color: rgba(245, 108, 108, 0.2);
  z-index: 10;
  pointer-events: none;
}

.riding-stamp-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-left: 2px dashed #f56c6c;
}

.riding-stamp-preview {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(245, 108, 108, 0.1);
  border: 2px dashed #f56c6c;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stamp-icon {
  font-size: 20px;
  color: #f56c6c;
}

.signature-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.signature-element {
  position: absolute;
  border: 2px dashed #409eff;
  background: rgba(64, 158, 255, 0.1);
  cursor: move;
  pointer-events: all;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
  min-height: 40px;
}

.signature-element:hover {
  border-color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

.signature-element.is-selected {
  border-style: solid;
  z-index: 100;
}

.signature-element.signature {
  border-color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.signature-element.stamp {
  border-color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

.signature-element.text {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

/* 自定义印章样式 */
.custom-stamp {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-weight: bold;
  border-style: solid;
  box-sizing: border-box;
  word-break: break-all;
  line-height: 1.2;
  padding: 4px;
}

.custom-stamp.circle {
  border-radius: 50%;
}

.custom-stamp.square {
  border-radius: 4px;
}

.signature-element.date {
  border-color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

.signature-content {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #303133;
  text-align: center;
  padding: 4px;
}

.signature-icon {
  font-size: 16px;
  color: #e6a23c;
}

.signature-controls {
  position: absolute;
  top: -40px;
  right: 0;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 101;
}

/* 调整大小控件 */
.resize-handle {
  position: absolute;
  bottom: -8px;
  right: -8px;
  width: 16px;
  height: 16px;
  background-color: white;
  border: 2px solid #409eff;
  border-radius: 50%;
  cursor: nwse-resize;
  z-index: 101;
}

/* 编辑对话框样式 */
.position-inputs {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>